package com.cheys.webapp.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;

public class HTMLFilter implements Filter {

	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub

	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		try {
			String root_path = System.getProperty("webapp.root");
			File file = new File(root_path+"_index.html");
			if(!file.exists()){
				Properties p = new Properties();
				LogUtil.getLogger(HTMLCreatorListener.class).debug("start HTMLCreatorListner...");
				String p_path = root_path+"/WEB-INF/config.properties";
				FileInputStream in = new FileInputStream(new File(p_path));
				p.load(in);
				String url = p.getProperty("init_url");
				HttpClient client = new HttpClient();
				client.getParams().setConnectionManagerTimeout(10000);
				PostMethod method = new PostMethod(url);
				int code = client.executeMethod(method);
				if(code == HttpStatus.SC_OK){
					LogUtil.getLogger(HTMLCreatorListener.class).debug("index.html is created...");
				}
			}
//			Thread t = new Thread(new PingThread( url));
//			t.start();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			chain.doFilter(request, response);
		}
	}

	public void destroy() {
		// TODO Auto-generated method stub

	}

}
